#import MSLogger
import time
import datetime
import pymssql
import sys
import pdb
RECONF_FILE = 'C:\safe\ms.reconf'
LOG_FILE    = 'C:\safe\ms_config_creator.log'
#MSProcessor.MSLogger.logInit(LOG_FILE, 4, True)

def update_object_config(device_params):
    cfg = open('objects.cfg', 'a')
    cfg.write('obj_id=%d obj_name=Object%d obj_skey=%s has_pgsm=yes has_contactid=yes has_gps=no' % (device_params[0], str(device_params[1])))
    cfg.close()
    reconf = open(RECONF_FILE, 'w')
    reconf.close()

def insert_device_to_CARONLINE(device_params):
    conn = pymssql.connect(host=r'192.168.0.81:3091', user='sa', password='ms', database='transferTest', login_timeout=10)
    c = conn.cursor()
    c.execute('INSERT INTO dbo._devices (uid) VALUES (%s)' % (str(device_params[1]))) #device mac
    conn.commit()
    c.execute("SELECT IDENT_CURRENT('dbo._devices')")
    t = c.fetchall()
    device_msid = int(t[0][0])
    device_name = 'dev' + str(device_params[0])
    device_pass = 'pass' + str(device_params[0])
    query = "INSERT INTO dbo._users (login, password, defaultDevice) VALUES ('%s', '%s', '%s')" % (device_name, device_pass, str(device_msid))
    c.execute(query)
    conn.commit()
    device_value = 'login=%s&password=%s' % (device_name, device_pass)
    device_ctime = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
    query = "INSERT INTO dbo.Security_values (\"key\", \"value\", \"date\") VALUES ('%s', '%s', '%s')" % (str(device_params[0]), device_value, device_ctime)
    c.execute(query)
    conn.commit()
    conn.close()
    return (device_params[0], device_params[1], device_msid, device_name, device_pass)

def request_params():
    sys.stdout.write('Enter Device Id: \n')
    device_pcnid   = int(sys.stdin.readline().strip('\n'))
    sys.stdout.write('Enter Divice MAC: \n')
    device_mac  = sys.stdin.readline().strip('\n')
    return (device_pcnid, device_mac)

while True:
    device_params = request_params()
    device_params = insert_device_to_CARONLINE(device_params)
    update_object_config(device_params)
